package com.cie2.janji.pages.users;

import java.io.File;
import java.util.Date;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.log4j.Logger;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.ApplicationGlobals;
import org.apache.tapestry5.upload.services.UploadedFile;

import com.cie2.janji.base.CieUserPage;
import com.cie2.janji.entities.BaseEntity;
import com.cie2.janji.services.BaseEntityService;
import com.cie2.janji.services.PromiseStatisticsService;

public class CreateEntity extends CieUserPage{

	static Logger logger = Logger.getLogger(CreateEntity.class.getName());

	private Long entityId;

	@Property
	private BaseEntity entity;

	// for file upload
	
	@Property
	private UploadedFile file;

//	not used
//	@Inject @Path("context:WEB-INF/web.xml")
//	private Asset myFile;
	
//	@Inject
//	private RequestGlobals requestGlobals;
	
	@Inject 
	private ApplicationGlobals applicationGlobals;
	   
	//services
	@Inject
	private BaseEntityService baseEntityService;
	    
	@Inject
	private PromiseStatisticsService statisticsService;

	
	@CommitAfter
	Object onSuccess() {

		if(null == entityId ) {
			addEntity();			
		}
		else
			updateEntity();
		
		
		return EntityList.class;
	}



	/**
	 * 
	 */
	private void addEntity() {
		if(file != null) {
			String realPath = applicationGlobals.getServletContext().getRealPath("/") ;
			
//			System.out.println("=== real path : " + realPath + ":"+file.getSize());
			String filename = "E_" + file.getFileName();
			File copied = new File(realPath + File.separatorChar +"images" + File.separatorChar  
					+ File.separatorChar +filename);
	
			file.write(copied);

			entity.setImage(filename);
			
		}

		entity.setCreatedDate(new Date());
		baseEntityService.add(entity);		
		statisticsService.createEntityStatistics(entity);
	}

	private void updateEntity() {
		entity.setUpdatedDate(new Date());
		baseEntityService.add(entity);
	}
	
	// error handling for upload file
	@Persist(PersistenceConstants.FLASH)
	@Property
	private String message;

	Object onUploadException(FileUploadException ex) {
		message = "Upload exception: " + ex.getMessage();

		return this;
	}

	Long onPassivate() {
		return entityId;
	}

	void onActivate(Long entityId) {
		this.entityId = entityId;
		entity = baseEntityService.load(entityId);
	}
}
